package com.renren.project.db.utils.bean;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.segments.MergeSegments;
import com.baomidou.mybatisplus.core.conditions.segments.NormalSegmentList;
import com.baomidou.mybatisplus.core.conditions.segments.OrderBySegmentList;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import org.apache.logging.log4j.util.Strings;

import java.util.Objects;
import java.util.function.Consumer;

/**
 * 自定义 QueryWrapper 用于在WHERE后追加条件
 * @date 2020/10/28
 */
public class BaidonQueryWrapper<T> extends QueryWrapper<T> {

    private String customOrderSqlSegment = Strings.EMPTY;

    public String getConcatCustomSqlSegment() {
        MergeSegments expression = getExpression();
        if (Objects.nonNull(expression)) {
            NormalSegmentList normal = expression.getNormal();
            String sqlSegment = getSqlSegment();
            if (com.baomidou.mybatisplus.core.toolkit.StringUtils.isNotBlank(sqlSegment)) {
                if (normal.isEmpty()) {
                    return sqlSegment;
                } else {
                    return "AND" + StringPool.SPACE + sqlSegment;
                }
            }
        }
        return StringPool.EMPTY;
    }

    public BaidonQueryWrapper<T> withRecursive(Consumer<BaidonQueryWrapper<T>> consumer) {
        consumer.accept(this);
        customOrderSqlSegment = expression.getOrderBy().getSqlSegment();
        expression.getOrderBy().clear();
        return this;
    }

    public String getCustomOrderSqlSegment() {
        MergeSegments expression = getExpression();
        if (Objects.nonNull(expression)) {
            OrderBySegmentList orderBy = expression.getOrderBy();
            if(!orderBy.isEmpty()){
                return orderBy.getSqlSegment();
            }
        }
        return StringPool.EMPTY;
    }

    public String getCustomWhereSqlSegment() {
        MergeSegments expression = getExpression();
        if (Objects.nonNull(expression)) {
            NormalSegmentList normal = expression.getNormal();
            String sqlSegment = normal.getSqlSegment();
            if (com.baomidou.mybatisplus.core.toolkit.StringUtils.isNotBlank(sqlSegment)) {
                if (normal.isEmpty()) {
                    return sqlSegment;
                } else {
                    return "WHERE" + StringPool.SPACE + sqlSegment;
                }
            }
        }
        return StringPool.EMPTY;
    }



}
